//
//  RequestManager.m
//  Request
//
//  Created by 梁晨 on 2017/6/23.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "RequestManager.h"
#import <AFNetworking.h>
#import "animationView.h"
#import "LoginViewController.h"
#import "HUD.h"

@implementation RequestManager

#pragma mark -------------------无提示文字的网络请求方法--------------------
+(void)RequstWithUrl:(NSString *)Url parmDic:(NSDictionary *)parmDic requestType:(RequestType)requestType Success:(Success )success error:(Error )error
{
    RequestManager *manager = [[RequestManager alloc]init];
    [manager RequstWithUrl:[NSString stringWithFormat:@"%@%@",KUrl,Url] parmDic:parmDic requestType:requestType Success:success error:error];
}

-(void)RequstWithUrl:(NSString *)Url parmDic:(NSDictionary *)parmDic requestType:(RequestType)requestType Success:(Success )success error:(Error )error
{
    self.success = success;
    
    self.error = error;
    
    parmDic = [self PerfectDic:parmDic];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    if (requestType == RequestGET)
    {
        // get请求的方法
        [manager GET:Url parameters:parmDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
        {
            // Get成功的回调
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];

            [self LoginOut:jsonDic];
            if ([jsonDic[@"flag"]isEqualToString:@"Success"])
            {
                [self SucessRequestReturnMainThread:jsonDic];
            }else
            {
                [self showTextHud:jsonDic[@"msg"]];
                [self SucessRequestReturnMainThread:jsonDic];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
        {
            
            self.error(error);
        }];
    }else
    {
        // post请求的方法
        [manager POST:Url parameters:parmDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
        {

            // post成功的回调
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            [self LoginOut:jsonDic];
            if ([jsonDic[@"flag"]isEqualToString:@"Success"])
            {
                [self SucessRequestReturnMainThread:jsonDic];
            }else
            {
                [self showTextHud:jsonDic[@"msg"]];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
        {
            
            self.error(error);
            
        }];
        
    }
}


#pragma mark -------------  有加载框 无提示文字的网络请求方法 ----------
+(void)ProgressRequestWithUrl:(NSString *)Url parmDic:(NSDictionary *)parmDic requestType:(RequestType)requestType view:(UIView *)view Success:(Success )success error:(Error )error
{
    RequestManager *manager = [[RequestManager alloc]init];
    [manager ProgressRequestWithUrl:[NSString stringWithFormat:@"%@%@",KUrl,Url] parmDic:parmDic requestType:requestType view:view Success:success error:error];
}

-(void)ProgressRequestWithUrl:(NSString *)Url parmDic:(NSDictionary *)parmDic requestType:(RequestType)requestType view:(UIView *)view Success:(Success )success error:(Error )error
{
    self.success = success;
    
    self.error = error;
    
    // 给参数字典添加固定参数
    parmDic = [self PerfectDic:parmDic];


    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /*
     ***
     *加载动画放在view上
     */
    
    [self ShowLoadHud:view];
    
    if (requestType == RequestGET)
    {
        // get请求的方法
        [manager GET:Url parameters:parmDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
         {
             // Get成功的回调
             NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
             [self LoginOut:jsonDic];
             if ([jsonDic[@"flag"]isEqualToString:@"Success"]) {
                 [self SucessRequestReturnMainThread:jsonDic];
             }
             // 保证加载动画的效果 用GCD保证动画能加载完整
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self DisMissLoadHud];

             });
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
         {
             self.error(error);
             // 保证加载动画的效果 用GCD保证动画能加载完整
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self DisMissLoadHud];
                
            });
         }];
    }else
    {
        // post请求的方法
        [manager POST:Url parameters:parmDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
         {
             // post成功的回调
             NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
             [self LoginOut:jsonDic];
             if ([jsonDic[@"flag"]isEqualToString:@"Success"]) {
                 [self SucessRequestReturnMainThread:jsonDic];
             }else
             {
                 [HUD showText:jsonDic[@"msg"] AfterTime:1];
             }
             
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 保证加载动画的效果 用GCD保证动画能加载完整
                 [self DisMissLoadHud];
             });
             
             
             
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             self.error(error);
             // 保证加载动画的效果 用GCD保证动画能加载完整
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self DisMissLoadHud];
                 
             });
         }];
        
    }

}


#pragma mark -------------- 无加载框 有提示文字的网络请求方法 ---------
+(void)HudRequestWithUrl:(NSString *)Url parmDic:(NSDictionary *)parmDic requestType:(RequestType)requestType view:(UIView *)view Success:(Success )success error:(Error )error
{
    RequestManager *manager = [[RequestManager alloc]init];
    [manager HudRequestWithUrl:[NSString stringWithFormat:@"%@%@",KUrl,Url] parmDic:parmDic requestType:requestType view:view Success:success error:error];
}

-(void)HudRequestWithUrl:(NSString *)Url parmDic:(NSDictionary *)parmDic requestType:(RequestType)requestType view:(UIView *)view Success:(Success )success error:(Error )error
{
    self.success = success;
    self.error = error;
    parmDic = [self PerfectDic:parmDic];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    if (requestType == RequestGET)
    {
        // get请求的方法
        [manager GET:Url parameters:parmDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
         {
             // Get成功的回调
             NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
             [self LoginOut:jsonDic];
             if ([jsonDic[@"flag"]isEqualToString:@"Success"])
             {
                 [self SucessRequestReturnMainThread:jsonDic];
                 [self showTextHud:jsonDic[@"msg"]];
             }else
             {
                 [self showTextHud:jsonDic[@"msg"]];
             }
             
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             self.error(error);
         }];
    }else
    {
        // post请求的方法
        [manager POST:Url parameters:parmDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
         {
             // post成功的回调
             NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
             [self LoginOut:jsonDic];
             if ([jsonDic[@"flag"]isEqualToString:@"Success"])
             {
                 [self SucessRequestReturnMainThread:jsonDic];
                 [self showTextHud:jsonDic[@"msg"]];
             }else
             {
                 [self showTextHud:jsonDic[@"msg"]];
             }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             self.error(error);
         }];
    }
    
}

+(void)NormalRequstWithUrl:(NSString *)Url parmDic:(NSDictionary *)parmDic requestType:(RequestType)requestType Success:(Success )success error:(Error )error
{
    RequestManager *manager = [[RequestManager alloc]init];
    [manager NormalRequstWithUrl:[NSString stringWithFormat:@"%@%@",KUrl,Url] parmDic:parmDic requestType:requestType Success:success error:error];
}

-(void)NormalRequstWithUrl:(NSString *)Url parmDic:(NSDictionary *)parmDic requestType:(RequestType)requestType Success:(Success )success error:(Error )error
{
    self.success = success;

    self.error = error;

    parmDic = [self PerfectDic:parmDic];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];


    if (requestType == RequestGET)
    {
        // get请求的方法
        [manager GET:Url parameters:parmDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
         {
             // Get成功的回调
             NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
             [self LoginOut:jsonDic];
            [self SucessRequestReturnMainThread:jsonDic];

         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
         {
             self.error(error);
         }];
    }else
    {
        // post请求的方法
        [manager POST:Url parameters:parmDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
         {

             // post成功的回调
             NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
             [self LoginOut:jsonDic];
//             [HUD showText:jsonDic[@"msg"] AfterTime:1];
            [self SucessRequestReturnMainThread:jsonDic];

         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
         {
             self.error(error);
         }];
    }
}

+(void)doUploadImage:(NSString *)methodString parameters:(id)parameter image:(UIImage*)image Success:(Success )success error:(Error )error
{
     RequestManager *manager = [[RequestManager alloc]init];
    [manager doUploadImage:methodString parameters:parameter image:image Success:success error:error];
}

-(void)doUploadImage:(NSString *)methodString parameters:(id)parameter image:(UIImage*)image Success:(Success )success error:(Error )error
{
    
}

//-(void)doUploadImage:(NSString *)methodString parameters:(id)parameter image:(UIImage*)image Success:(Success )success error:(Error )error
//{
//    self.success = success;
//    self.error = error;
//    parameter = [self PerfectDic:parameter];
//    AFHTTPSessionManager *manager=[self baseManager];
//    [manager POST:[NSString stringWithFormat:@"%@%@",KUrl,methodString] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
//     {
//         if (image)
//         {
//             // [formData appendPartWithFileData:[Utils compressImage:image] name:@"key1" fileName:@"key2" mimeType:@"image/jpeg"];
//         }
//
//     } progress:^(NSProgress * _Nonnull uploadProgress)
//     {
//         NSLog(@"uploadProgress----------%@",uploadProgress);
//     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//         NSString *result=[responseObject objectForKey:@"flag"];
//         if ([@"Success" isEqualToString:result])
//         {
//             success(responseObject[@"data"]);
//         }
//         else if([@"Error" isEqualToString:result])
//         {
//             error([responseObject objectForKey:@"msg"]);
//
//             dispatch_async(dispatch_get_main_queue(), ^{
//            });
//         }
//     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
//    {
//
//     }];
//
//}

-(AFHTTPSessionManager *)baseManager
{
    static AFHTTPSessionManager *manager=nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate,^{
        manager = [AFHTTPSessionManager manager];

        [manager.requestSerializer setTimeoutInterval:20];

        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"application/json", nil];
        if(false)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"网络错误" message:@"网络不可用,请检查您的网络" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
                [alertView show];
            });
        }
    });

    return manager;
}

#pragma mark ----------这里修改你的加载动画类型-----------
/**
 加载动画
 */
-(void)ShowLoadHud:(UIView *)view;
{
    [animationView showInView:view];
}


/**
 结束加载动画
 */
-(void)DisMissLoadHud
{
    [animationView dismiss];

}


-(void)showTextHud:(NSString *)text
{
    [HUD showText:text AfterTime:1];
}


/**
 回到主线程的回调
 
 @param jsonDic 回调的json 只是获取data里面的数据
 */
-(void)SucessRequestReturnMainThread:(NSDictionary *)jsonDic;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (![jsonDic[@"flag"]isEqualToString:@"Success"]) {
            [HUD showText:jsonDic[@"msg"] AfterTime:1];
             self.success(jsonDic[@"data"]);
        }else
        {
             self.success(jsonDic[@"data"]);
        }
    });
}


/**
  给字典添加固定的键值对
 
 @param parmDic 原字典
 @return 返回添加字段后的字典
 */
-(NSMutableDictionary *)PerfectDic:(NSDictionary *)parmDic
{
    parmDic = [parmDic mutableCopy];

    if ([[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken])
    {
        [parmDic setValue:[[NSUserDefaults standardUserDefaults]objectForKey:kUserId] forKey:@"uid"];
        [parmDic setValue:[[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken]forKey:@"access_token"];
    }
    return [parmDic mutableCopy];
}

-(void)LoginOut:(NSDictionary *)jsonDic
{
    if ([jsonDic[@"errcode"] isEqual:@10086])
    {
        UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
        UIViewController *vc = window.rootViewController;

        UIAlertController *Ac = [UIAlertController alertControllerWithTitle:@"账号在别处登录，请重新登录" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *Commit = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action)
        {
            [UserInfoManage logout];
            UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
            window.rootViewController = [[LoginViewController alloc]init];
        }];
        [Ac addAction:Commit];
        [vc presentViewController:Ac animated:YES completion:nil];
    }
}

/**
 做数据缓存
 */
-(void)SetURLCache
{
    
}





@end
